//
//  WSThreeColorGradientButton.m
//  CharonTVProject
//
//  Created by karong on 2023/8/10.
//

#import "WSThreeColorGradientButton.h"
@interface WSThreeColorGradientButton ()

@property (nonatomic, assign) CGRect gradientLayerFrame;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;

@end
@implementation WSThreeColorGradientButton

- (void)layoutSubviews {
    [super layoutSubviews];
    _gradientLayer.frame = self.bounds;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    [self.gradientLayer removeFromSuperlayer];
    [self setupGradientLayer];
}

- (void)setLayerFrame:(CGRect)frame {
    self.gradientLayerFrame = frame;
    self.gradientLayer.frame = self.gradientLayerFrame;
}

- (void)setupGradientLayer {
    CAGradientLayer *layer = [[CAGradientLayer alloc] init];
    CGRect frame = self.bounds;
    
    if (CGRectEqualToRect(self.gradientLayerFrame, CGRectZero)) {
        layer.frame = frame;
    } else {
        layer.frame = self.gradientLayerFrame;
    }
    
    if (self.color1 && self.color2 && self.color3) {
        layer.colors = @[(__bridge id)self.color1.CGColor,
                         (__bridge id)self.color2.CGColor,
                         (__bridge id)self.color3.CGColor];
    } else {
        layer.colors = @[(__bridge id)[UIColor colorFromHexRGB:@"F6CCB1"].CGColor,
                         (__bridge id)[UIColor colorFromHexRGB:@"FFFCFB"].CGColor,
                         (__bridge id)[UIColor colorFromHexRGB:@"F7D8C0"].CGColor];
    }
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(1, 0);
    [self.layer insertSublayer:layer atIndex:0];
    self.gradientLayer = layer;
}

- (void)removeColorLayer {
    [self.gradientLayer removeFromSuperlayer];
    self.gradientLayer = nil;
}


- (void)resetCorlor1:(UIColor *)color1 color2:(UIColor *)color2 color3:(nonnull UIColor *)color3 {
    _color1 = color1;
    _color2 = color2;
    _color2 = color3;

    [self.gradientLayer removeFromSuperlayer];
    self.gradientLayer = nil;
    
    [self setupGradientLayer];
}

@end
